#include "mainwindow.h"
#include <QFile>
#include <QFileDialog>
#include <QTextStream>
#include <QMessageBox>
#include <QMenuBar>
#include <QToolBar>
#include <QStatusBar>
#include <QAction>
#include <QTabBar>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QWebEngineSettings>
#include <QMimeData>
#include <QCloseEvent>
#include <QTimer>
#include <QDebug>

// 自定义文本编辑器，支持语法高亮
class MarkdownEditor : public QTextEdit {
    Q_OBJECT
public:
    explicit MarkdownEditor(QWidget *parent = nullptr) : QTextEdit(parent) {
        setAcceptRichText(false);
        setLineWrapMode(QTextEdit::WidgetWidth);
        setTabStopDistance(QFontMetricsF(font()).horizontalAdvance(' ') * 4);
        // 启用拖放支持
        setAcceptDrops(true);
        setDragEnabled(true);
    }

protected:
    void keyPressEvent(QKeyEvent *event) override {
        // 处理Tab键缩进
        if (event->key() == Qt::Key_Tab) {
            insertPlainText("    ");
            event->ignore();
            return;
        } else if (event->key() == Qt::Key_Backtab) {
            // 处理Shift+Tab取消缩进
            QTextCursor cursor = textCursor();
            if (cursor.hasSelection()) {
                // 多行缩进处理
                cursor.beginEditBlock();
                int start = cursor.selectionStart();
                int end = cursor.selectionEnd();
                cursor.setPosition(start);
                int startLine = cursor.blockNumber();
                cursor.setPosition(end);
                int endLine = cursor.blockNumber();

                for (int i = startLine; i <= endLine; ++i) {
                    cursor.movePosition(QTextCursor::StartOfLine);
                    if (cursor.columnNumber() >= 4) {
                        cursor.movePosition(QTextCursor::Right, QTextCursor::KeepAnchor, 4);
                        cursor.removeSelectedText();
                    }
                    cursor.movePosition(QTextCursor::NextBlock);
                }
                cursor.endEditBlock();
            } else {
                // 单行缩进处理
                cursor.movePosition(QTextCursor::StartOfLine);
                if (cursor.columnNumber() >= 4) {
                    cursor.movePosition(QTextCursor::Right, QTextCursor::KeepAnchor, 4);
                    cursor.removeSelectedText();
                }
            }
            event->ignore();
            return;
        }
        QTextEdit::keyPressEvent(event);
    }
};

MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent),
    m_tabWidget(new QTabWidget(this)),
    m_mainSplitter(new QSplitter(Qt::Horizontal, this)),
    m_fileWatcher(new QFileSystemWatcher(this)),
    m_autoSaveTimer(new QTimer(this)),
    m_renderer(new MarkdownRenderer(this)),
    m_settings(new SettingsManager(this)),
    m_historyManager(new HistoryManager(this)),
    m_pluginManager(new PluginManager(this)),
    m_previewEnabled(true)
{
    initUI();
    createMenus();
    createToolbars();
    createStatusBar();
    applySettings();

    // 连接信号槽
    connect(m_renderer, &MarkdownRenderer::renderingFinished, this, &MainWindow::handleRenderingFinished);
    connect(m_tabWidget, &QTabWidget::currentChanged, this, &MainWindow::handleTabChanged);
    connect(m_tabWidget, &QTabWidget::tabCloseRequested, this, &MainWindow::closeCurrentTab);
    connect(m_fileWatcher, &QFileSystemWatcher::fileChanged, this, &MainWindow::handleFileChanged);
    connect(m_autoSaveTimer, &QTimer::timeout, this, &MainWindow::autoSave);

    // 启动自动保存定时器 (5分钟)
    m_autoSaveTimer->start(5 * 60 * 1000);

    // 加载插件
    m_pluginManager->loadPlugins();

    // 创建新文件
    newFile();
}

MainWindow::~MainWindow()
{
    delete m_settings;
    delete m_historyManager;
    delete m_pluginManager;
}

void MainWindow::initUI()
{
    // 设置窗口属性
    setMinimumSize(1024, 768);
    setAcceptDrops(true);

    // 配置标签页
    m_tabWidget->setTabsClosable(true);
    m_tabWidget->setMovable(true);
    m_tabWidget->setDocumentMode(true);

    // 设置主分割器
    setCentralWidget(m_mainSplitter);
    m_mainSplitter->addWidget(m_tabWidget);

    // 设置样式
    loadEditorStyle();
}

void MainWindow::createMenus()
{
    // 文件菜单
    QMenu *fileMenu = menuBar()->addMenu(tr("文件(&F)"));

    // 新建动作
    QAction *newAct = new QAction(QIcon::fromTheme("document-new"), tr("新建(&N)"), this);
    newAct->setShortcuts(QKeySequence::New);
    newAct->setStatusTip(tr("创建新文件"));
    connect(newAct, &QAction::triggered, this, &MainWindow::newFile);
    fileMenu->addAction(newAct);

    // 打开动作
    QAction *openAct = new QAction(QIcon::fromTheme("document-open"), tr("打开(&O)"), this);
    openAct->setShortcuts(QKeySequence::Open);
    openAct->setStatusTip(tr("打开现有文件"));
    connect(openAct, &QAction::triggered, this, &MainWindow::openFile);
    fileMenu->addAction(openAct);

    // 最近文件子菜单
    QMenu *recentMenu = fileMenu->addMenu(tr("最近文件(&R)"));
    connect(recentMenu, &QMenu::aboutToShow, [this, recentMenu]() {
        recentMenu->clear();
        QStringList recentFiles = m_historyManager->recentFiles();
        if (recentFiles.isEmpty()) {
            recentMenu->addAction(tr("无最近文件")).setEnabled(false);
            return;
        }
        for (const QString &file : recentFiles) {
            QAction *act = recentMenu->addAction(QFileInfo(file).fileName());
            act->setData(file);
            connect(act, &QAction::triggered, [this, file]() { openFile(file); });
        }
        recentMenu->addSeparator();
        QAction *clearAct = recentMenu->addAction(tr("清除最近文件"));
        connect(clearAct, &QAction::triggered, m_historyManager, &HistoryManager::clearRecentFiles);
    });

    fileMenu->addSeparator();

    // 保存动作
    QAction *saveAct = new QAction(QIcon::fromTheme("document-save"), tr("保存(&S)"), this);
    saveAct->setShortcuts(QKeySequence::Save);
    saveAct->setStatusTip(tr("保存当前文件"));
    connect(saveAct, &QAction::triggered, this, &MainWindow::saveFile);
    fileMenu->addAction(saveAct);

    // 另存为动作
    QAction *saveAsAct = new QAction(QIcon::fromTheme("document-save-as"), tr("另存为(&A)"), this);
    saveAsAct->setShortcuts(QKeySequence::SaveAs);
    saveAsAct->setStatusTip(tr("将当前文件另存为..."));
    connect(saveAsAct, &QAction::triggered, this, &MainWindow::saveFileAs);
    fileMenu->addAction(saveAsAct);

    fileMenu->addSeparator();

    // 关闭标签页动作
    QAction *closeTabAct = new QAction(tr("关闭标签页(&W)"), this);
    closeTabAct->setShortcuts(QKeySequence::Close);
    closeTabAct->setStatusTip(tr("关闭当前标签页"));
    connect(closeTabAct, &QAction::triggered, this, &MainWindow::closeCurrentTab);
    fileMenu->addAction(closeTabAct);

    // 退出动作
    QAction *exitAct = new QAction(QIcon::fromTheme("application-exit"), tr("退出(&X)"), this);
    exitAct->setShortcuts(QKeySequence::Quit);
    exitAct->setStatusTip(tr("退出应用程序"));
    connect(exitAct, &QAction::triggered, this, &QMainWindow::close);
    fileMenu->addAction(exitAct);

    // 编辑菜单
    QMenu *editMenu = menuBar()->addMenu(tr("编辑(&E)"));
    // 编辑动作将在这里添加

    // 视图菜单
    QMenu *viewMenu = menuBar()->addMenu(tr("视图(&V)"));

    // 预览模式动作
    QAction *previewAct = new QAction(tr("预览模式(&P)"), this);
    previewAct->setCheckable(true);
    previewAct->setChecked(m_previewEnabled);
    previewAct->setShortcut(Qt::ALT + Qt::Key_P);
    previewAct->setStatusTip(tr("切换预览模式"));
    connect(previewAct, &QAction::triggered, this, &MainWindow::togglePreviewMode);
    viewMenu->addAction(previewAct);

    // 主题子菜单
    QMenu *themeMenu = viewMenu->addMenu(tr("主题(&T)"));

    QAction *lightAct = new QAction(tr("浅色主题"), this);
    lightAct->setCheckable(true);
    lightAct->setChecked(m_settings->theme() == SettingsManager::LightTheme);
    connect(lightAct, &QAction::triggered, [this]() { switchTheme(SettingsManager::LightTheme); });
    themeMenu->addAction(lightAct);

    QAction *darkAct = new QAction(tr("深色主题"), this);
    darkAct->setCheckable(true);
    darkAct->setChecked(m_settings->theme() == SettingsManager::DarkTheme);
    connect(darkAct, &QAction::triggered, [this]() { switchTheme(SettingsManager::DarkTheme); });
    themeMenu->addAction(darkAct);

    // 设置动作
    QAction *settingsAct = new QAction(QIcon::fromTheme("preferences-system"), tr("设置(&S)"), this);
    settingsAct->setShortcut(Qt::ALT + Qt::Key_S);
    settingsAct->setStatusTip(tr("打开设置对话框"));
    connect(settingsAct, &QAction::triggered, this, &MainWindow::applySettings);
    viewMenu->addSeparator();
    viewMenu->addAction(settingsAct);

    // 帮助菜单
    QMenu *helpMenu = menuBar()->addMenu(tr("帮助(&H)"));
    // 帮助动作将在这里添加
}

void MainWindow::createToolbars()
{
    // 文件工具栏
    QToolBar *fileToolbar = addToolBar(tr("文件"));
    fileToolbar->setObjectName("fileToolbar");
    fileToolbar->setAllowedAreas(Qt::TopToolBarArea | Qt::LeftToolBarArea);

    // 添加文件相关动作
    QAction *newAct = findChild<QAction*>(tr("新建(&N)"));
    if (newAct) fileToolbar->addAction(newAct);

    QAction *openAct = findChild<QAction*>(tr("打开(&O)"));
    if (openAct) fileToolbar->addAction(openAct);

    QAction *saveAct = findChild<QAction*>(tr("保存(&S)"));
    if (saveAct) fileToolbar->addAction(saveAct);

    fileToolbar->addSeparator();

    // 编辑工具栏
    QToolBar *editToolbar = addToolBar(tr("编辑"));
    editToolbar->setObjectName("editToolbar");
    editToolbar->setAllowedAreas(Qt::TopToolBarArea | Qt::LeftToolBarArea);

    // 格式工具栏
    QToolBar *formatToolbar = addToolBar(tr("格式"));
    formatToolbar->setObjectName("formatToolbar");
    formatToolbar->setAllowedAreas(Qt::TopToolBarArea | Qt::LeftToolBarArea);

    // 添加格式相关动作
    // 加粗
    QAction *boldAct = new QAction(QIcon::fromTheme("format-text-bold"), tr("加粗(B)"), this);
    boldAct->setShortcut(Qt::CTRL + Qt::Key_B);
    connect(boldAct, &QAction::triggered, [this]() {
        wrapSelectionWithMarkdown("**");
    });
    formatToolbar->addAction(boldAct);

    // 斜体
    QAction *italicAct = new QAction(QIcon::fromTheme("format-text-italic"), tr("斜体(I)"), this);
    italicAct->setShortcut(Qt::CTRL + Qt::Key_I);
    connect(italicAct, &QAction::triggered, [this]() {
        wrapSelectionWithMarkdown("*");
    });
    formatToolbar->addAction(italicAct);

    // 标题
    QAction *headingAct = new QAction(QIcon::fromTheme("format-text-heading"), tr("标题(H)"), this);
    headingAct->setShortcut(Qt::CTRL + Qt::Key_H);
    connect(headingAct, &QAction::triggered, [this]() {
        wrapSelectionWithMarkdown("# ");
    });
    formatToolbar->addAction(headingAct);

    // 代码块
    QAction *codeAct = new QAction(QIcon::fromTheme("insert-code"), tr("代码块(C)"), this);
    codeAct->setShortcut(Qt::CTRL + Qt::Key_K);
    connect(codeAct, &QAction::triggered, [this]() {
        wrapSelectionWithMarkdown("```\n", "\n```");
    });
    formatToolbar->addAction(codeAct);

    // 链接
    QAction *linkAct = new QAction(QIcon::fromTheme("insert-link"), tr("链接(L)"), this);
    linkAct->setShortcut(Qt::CTRL + Qt::Key_L);
    connect(linkAct, &QAction::triggered, [this]() {
        wrapSelectionWithMarkdown("[", "]()");
    });
    formatToolbar->addAction(linkAct);

    // 图片
    QAction *imageAct = new QAction(QIcon::fromTheme("insert-image"), tr("图片(I)"), this);
    imageAct->setShortcut(Qt::CTRL + Qt::Key_G);
    connect(imageAct, &QAction::triggered, [this]() {
        wrapSelectionWithMarkdown("![", "]()");
    });
    formatToolbar->addAction(imageAct);

    formatToolbar->addSeparator();

    // 预览工具栏
    QToolBar *previewToolbar = addToolBar(tr("预览"));
    previewToolbar->setObjectName("previewToolbar");
    previewToolbar->setAllowedAreas(Qt::TopToolBarArea | Qt::LeftToolBarArea);

    QAction *previewAct = findChild<QAction*>(tr("预览模式(&P)"));
    if (previewAct) previewToolbar->addAction(previewAct);
}

void MainWindow::createStatusBar()
{
    statusBar()->showMessage(tr("就绪"));
    setStatusBar(statusBar());
}

void MainWindow::updateWindowTitle(const QString &path)
{
    QString title;
    if (path.isEmpty()) {
        title = tr("未命名");
    } else {
        title = QFileInfo(path).fileName();
    }

    // 添加修改标记
    if (currentEditor() && currentEditor()->document()->isModified()) {
        title += " *";
    }

    title += " - " + tr("Markdown编辑器");
    setWindowTitle(title);
}

QTextEdit *MainWindow::currentEditor() const
{
    if (m_tabWidget->count() == 0) return nullptr;

    QWidget *currentWidget = m_tabWidget->currentWidget();
    if (!currentWidget) return nullptr;

    QSplitter *splitter = qobject_cast<QSplitter*>(currentWidget);
    if (!splitter || splitter->count() == 0) return nullptr;

    return qobject_cast<QTextEdit*>(splitter->widget(0));
}

QWebEngineView *MainWindow::currentPreview() const
{
    if (m_tabWidget->count() == 0) return nullptr;

    QWidget *currentWidget = m_tabWidget->currentWidget();
    if (!currentWidget) return nullptr;

    QSplitter *splitter = qobject_cast<QSplitter*>(currentWidget);
    if (!splitter || splitter->count() < 2) return nullptr;

    return qobject_cast<QWebEngineView*>(splitter->widget(1));
}

void MainWindow::loadEditorStyle()
{
    // 加载编辑器样式表
    QFile styleFile(":/styles/editor.css");
    if (styleFile.open(QFile::ReadOnly)) {
        QString style = QLatin1String(styleFile.readAll());
        // 应用到所有编辑器
        for (int i = 0; i < m_tabWidget->count(); ++i) {
            QWidget *widget = m_tabWidget->widget(i);
            QSplitter *splitter = qobject_cast<QSplitter*>(widget);
            if (splitter && splitter->count() > 0) {
                QTextEdit *editor = qobject_cast<QTextEdit*>(splitter->widget(0));
                if (editor) {
                    editor->setStyleSheet(style);
                }
            }
        }
    }
}

void MainWindow::wrapSelectionWithMarkdown(const QString &prefix, const QString &suffix)
{
    QTextEdit *editor = currentEditor();
    if (!editor) return;

    QTextCursor cursor = editor->textCursor();
    QString selectedText = cursor.selectedText();
    bool hasSelection = !selectedText.isEmpty();

    cursor.beginEditBlock();

    if (hasSelection) {
        cursor.insertText(prefix + selectedText + suffix);
    } else {
        cursor.insertText(prefix + suffix);
        cursor.movePosition(QTextCursor::Left, QTextCursor::MoveAnchor, suffix.length());
    }

    cursor.endEditBlock();
    editor->setTextCursor(cursor);
    editor->setFocus();
}

void MainWindow::newFile()
{
    // 创建新的编辑器和预览视图
    QSplitter *splitter = new QSplitter(Qt::Horizontal);
    splitter->setObjectName("editorSplitter");

    MarkdownEditor *editor = new MarkdownEditor();
    editor->setObjectName("editor");
    connect(editor->document(), &QTextDocument::contentsChanged, this, &MainWindow::handleTextChanged);
    connect(editor, &QTextEdit::cursorPositionChanged, [this, editor]() {
        QTextCursor cursor = editor->textCursor();
        int line = cursor.blockNumber() + 1;
        int column = cursor.columnNumber() + 1;
        statusBar()->showMessage(tr("行 %1, 列 %2").arg(line).arg(column));
    });

    QWebEngineView *preview = new QWebEngineView();
    preview->setObjectName("preview");
    preview->settings()->setAttribute(QWebEngineSettings::LocalContentCanAccessRemoteUrls, true);
    preview->settings()->setAttribute(QWebEngineSettings::AllowRunningInsecureContent, true);

    splitter->addWidget(editor);
    splitter->addWidget(preview);
    splitter->setSizes({600, 400});

    // 添加到标签页
    int index = m_tabWidget->addTab(splitter, tr("未命名"));
    m_tabWidget->setCurrentIndex(index);
    editor->setFocus();

    updateWindowTitle();
    loadEditorStyle();
}

bool MainWindow::openFile(const QString &path)
{
    QString filePath = path;

    if (filePath.isEmpty()) {
        filePath = QFileDialog::getOpenFileName(this, tr("打开文件"), QString(),
            tr("Markdown文件 (*.md *.markdown *.mdown *.mkd);;所有文件 (*)"));

        if (filePath.isEmpty()) return false;
    }

    // 检查文件是否已打开
    for (int i = 0; i < m_tabWidget->count(); ++i) {
        QVariant data = m_tabWidget->tabData(i);
        if (data.toString() == filePath) {
            m_tabWidget->setCurrentIndex(i);
            return true;
        }
    }

    // 读取文件内容
    QFile file(filePath);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        QMessageBox::warning(this, tr("错误"),
            tr("无法打开文件 %1:\n%2").arg(filePath).arg(file.errorString()));
        return false;
    }

    // 创建新标签页
    newFile();
    m_tabWidget->setCurrentIndex(m_tabWidget->count() - 1);

    // 设置文件内容
    QTextStream in(&file);
    QString content = in.readAll();
    currentEditor()->setPlainText(content);
    currentEditor()->document()->setModified(false);

    // 设置标签页标题
    m_tabWidget->setTabText(m_tabWidget->currentIndex(), QFileInfo(filePath).fileName());
    m_tabWidget->setTabData(m_tabWidget->currentIndex(), filePath);

    // 添加到文件监视器
    if (!m_fileWatcher->files().contains(filePath)) {
        m_fileWatcher->addPath(filePath);
    }

    // 更新窗口标题
    updateWindowTitle(filePath);

    // 添加到最近文件历史
    m_historyManager->addRecentFile(filePath);

    return true;
}

bool MainWindow::saveFile()
{
    if (currentFilePath().isEmpty()) {
        return saveFileAs();
    }

    return saveFileToPath(currentFilePath());
}

bool MainWindow::saveFileAs()
{
    QString filePath = QFileDialog::getSaveFileName(this, tr("另存为"), QString(),
        tr("Markdown文件 (*.md);;所有文件 (*)"));

    if (filePath.isEmpty()) return false;

    // 添加.md扩展名（如果需要）
    if (!filePath.endsWith(".md", Qt::CaseInsensitive) &&
        !filePath.endsWith(".markdown", Qt::CaseInsensitive)) {
        filePath += ".md";
    }

    return saveFileToPath(filePath);
}

bool MainWindow::saveFileToPath(const QString &path)
{
    if (!currentEditor()) return false;

    QFile file(path);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        QMessageBox::warning(this, tr("错误"),
            tr("无法保存文件 %1:\n%2").arg(path).arg(file.errorString()));
        return false;
    }

    QTextStream out(&file);
    out << currentEditor()->toPlainText();

    currentEditor()->document()->setModified(false);
    m_tabWidget->setTabText(m_tabWidget->currentIndex(), QFileInfo(path).fileName());
    m_tabWidget->setTabData(m_tabWidget->currentIndex(), path);

    // 更新文件监视器
    if (!m_fileWatcher->files().contains(path)) {
        m_fileWatcher->addPath(path);
    }

    updateWindowTitle(path);
    statusBar()->showMessage(tr("文件已保存: %1").arg(path), 2000);

    // 添加到最近文件历史
    m_historyManager->addRecentFile(path);

    emit fileSaved(path);
    return true;
}

void MainWindow::closeCurrentTab(int index)
{
    if (m_tabWidget->count() == 1) {
        // 最后一个标签页，创建新文件代替关闭
        currentEditor()->document()->setModified(false);
        currentEditor()->clear();
        m_tabWidget->setTabText(0, tr("未命名"));
        m_tabWidget->setTabData(0, QString());
        updateWindowTitle();
        return;
    }

    int tabIndex = index == -1 ? m_tabWidget->currentIndex() : index;
    if (tabIndex < 0 || tabIndex >= m_tabWidget->count()) return;

    QWidget *widget = m_tabWidget->widget(tabIndex);
    if (!widget) return;

    // 检查是否需要保存
    QTextEdit *editor = qobject_cast<QTextEdit*>(qobject_cast<QSplitter*>(widget)->widget(0));
    if (editor && editor->document()->isModified()) {
        QString title = m_tabWidget->tabText(tabIndex);
        QMessageBox::StandardButton ret = QMessageBox::warning(this, tr("保存更改"),
            tr("'%1' 已被修改。\n是否保存更改?").arg(title),
            QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel);

        if (ret == QMessageBox::Cancel) return;
        if (ret == QMessageBox::Save) {
            if (!saveFile()) return;
        }
    }

    // 从文件监视器中移除
    QString path = m_tabWidget->tabData(tabIndex).toString();
    if (!path.isEmpty() && m_fileWatcher->files().contains(path)) {
        m_fileWatcher->removePath(path);
    }

    // 关闭标签页
    m_tabWidget->removeTab(tabIndex);
    delete widget;

    updateWindowTitle(currentFilePath());
}

void MainWindow::handleTextChanged()
{
    updateWindowTitle(currentFilePath());

    // 触发渲染
    if (currentEditor() && currentPreview() && m_previewEnabled) {
        QString text = currentEditor()->toPlainText();
        m_renderer->render(text);
        emit contentChanged(text);
    }
}

void MainWindow::handleRenderingFinished(const QString &html)
{
    if (currentPreview()) {
        currentPreview()->setHtml(html);
    }
}

void MainWindow::handleTabChanged(int index)
{
    if (index < 0 || index >= m_tabWidget->count()) {
        updateWindowTitle();
        return;
    }

    QString path = m_tabWidget->tabData(index).toString();
    updateWindowTitle(path);

    // 触发当前内容的渲染
    if (currentEditor() && currentPreview() && m_previewEnabled) {
        QString text = currentEditor()->toPlainText();
        m_renderer->render(text);
    }
}

void MainWindow::handleFileChanged(const QString &path)
{
    // 检查文件是否仍然存在
    if (!QFile::exists(path)) return;

    // 查找对应的标签页
    for (int i = 0; i < m_tabWidget->count(); ++i) {
        if (m_tabWidget->tabData(i).toString() == path) {
            // 询问用户是否重新加载
            QMessageBox::StandardButton ret = QMessageBox::information(this, tr("文件已更改"),
                tr("文件 '%1' 已在外部修改。\n是否重新加载?").arg(QFileInfo(path).fileName()),
                QMessageBox::Yes | QMessageBox::No);

            if (ret == QMessageBox::Yes) {
                QFile file(path);
                if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
                    QTextStream in(&file);
                    QString content = in.readAll();

                    // 保存当前编辑器状态
                    bool wasModified = currentEditor()->document()->isModified();

                    // 锁定信号以防止递归
                    disconnect(currentEditor()->document(), &QTextDocument::contentsChanged, this, &MainWindow::handleTextChanged);
                    currentEditor()->setPlainText(content);
                    currentEditor()->document()->setModified(wasModified);
                    connect(currentEditor()->document(), &QTextDocument::contentsChanged, this, &MainWindow::handleTextChanged);

                    // 重新添加到文件监视器（文件可能已被替换）
                    m_fileWatcher->removePath(path);
                    m_fileWatcher->addPath(path);
                }
            }
            break;
        }
    }
}

void MainWindow::autoSave()
{
    // 自动保存所有修改的文件
    for (int i = 0; i < m_tabWidget->count(); ++i) {
        m_tabWidget->setCurrentIndex(i);
        QTextEdit *editor = currentEditor();
        if (editor && editor->document()->isModified() && !currentFilePath().isEmpty()) {
            saveFile();
        }
    }

    if (m_tabWidget->count() > 0) {
        m_tabWidget->setCurrentIndex(0);
    }

    statusBar()->showMessage(tr("自动保存完成"), 2000);
}

void MainWindow::togglePreviewMode(bool enabled)
{
    m_previewEnabled = enabled;

    for (int i = 0; i < m_tabWidget->count(); ++i) {
        QWidget *widget = m_tabWidget->widget(i);
        QSplitter *splitter = qobject_cast<QSplitter*>(widget);
        if (splitter && splitter->count() > 1) {
            QWebEngineView *preview = qobject_cast<QWebEngineView*>(splitter->widget(1));
            if (preview) {
                preview->setVisible(enabled);
                if (enabled) {
                    splitter->setSizes({600, 400});
                } else {
                    splitter->setSizes({1000, 0});
                }
            }
        }
    }

    // 如果启用预览，立即渲染当前内容
    if (enabled && currentEditor() && currentPreview()) {
        m_renderer->render(currentEditor()->toPlainText());
    }
}

void MainWindow::switchTheme(SettingsManager::Theme theme)
{
    m_settings->setTheme(theme);
    m_settings->save();

    // 加载新主题样式表
    QFile styleFile(theme == SettingsManager::DarkTheme ? ":/styles/dark.qss" : ":/styles/light.qss");
    if (styleFile.open(QFile::ReadOnly)) {
        QString style = QLatin1String(styleFile.readAll());
        setStyleSheet(style);
    }

    // 更新预览主题
    if (currentPreview()) {
        handleTextChanged(); // 触发重新渲染
    }

    // 更新菜单项状态
    QAction *lightAct = findChild<QAction*>(tr("浅色主题"));
    if (lightAct) lightAct->setChecked(theme == SettingsManager::LightTheme);

    QAction *darkAct = findChild<QAction*>(tr("深色主题"));
    if (darkAct) darkAct->setChecked(theme == SettingsManager::DarkTheme);
}

void MainWindow::applySettings()
{
    // 应用主题设置
    switchTheme(m_settings->theme());

    // 应用字体设置
    QFont font = m_settings->font();
    for (int i = 0; i < m_tabWidget->count(); ++i) {
        QWidget *widget = m_tabWidget->widget(i);
        QSplitter *splitter = qobject_cast<QSplitter*>(widget);
        if (splitter && splitter->count() > 0) {
            QTextEdit *editor = qobject_cast<QTextEdit*>(splitter->widget(0));
            if (editor) {
                editor->setFont(font);
            }
        }
    }

    // 应用预览设置
    togglePreviewMode(m_settings->previewEnabled());
}

void MainWindow::closeEvent(QCloseEvent *event)
{
    // 检查所有标签页是否需要保存
    bool allSaved = true;

    for (int i = 0; i < m_tabWidget->count(); ++i) {
        m_tabWidget->setCurrentIndex(i);
        if (currentEditor() && currentEditor()->document()->isModified()) {
            allSaved = false;
            break;
        }
    }

    if (!allSaved) {
        QMessageBox::StandardButton ret = QMessageBox::warning(this, tr("保存更改"),
            tr("有文件已被修改。\n是否保存更改并退出?"),
            QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel);

        if (ret == QMessageBox::Cancel) {
            event->ignore();
            return;
        } else if (ret == QMessageBox::Save) {
            for (int i = 0; i < m_tabWidget->count(); ++i) {
                m_tabWidget->setCurrentIndex(i);
                if (currentEditor() && currentEditor()->document()->isModified()) {
                    if (!saveFile()) {
                        event->ignore();
                        return;
                    }
                }
            }
        }
    }

    // 保存窗口状态
    m_settings->setWindowSize(size());
    m_settings->setWindowPosition(pos());
    m_settings->save();

    event->accept();
}

void MainWindow::dragEnterEvent(QDragEnterEvent *event)
{
    if (event->mimeData()->hasUrls()) {
        event->acceptProposedAction();
    }
}

void MainWindow::dropEvent(QDropEvent *event)
{
    const QMimeData *mimeData = event->mimeData();
    if (mimeData->hasUrls()) {
        QList<QUrl> urlList = mimeData->urls();
        for (const QUrl &url : urlList) {
            if (url.isLocalFile()) {
                openFile(url.toLocalFile());
            }
        }
        event->acceptProposedAction();
    }
}

QString MainWindow::currentFilePath() const
{
    if (m_tabWidget->count() == 0) return QString();
    return m_tabWidget->tabData(m_tabWidget->currentIndex()).toString();
}

void MainWindow::setWindowSize(const QSize &size)
{
    if (size.isValid() && size.width() > 800 && size.height() > 600) {
        resize(size);
    }
}

void MainWindow::setWindowPosition(const QPoint &pos)
{
    if (pos.isValid()) {
        move(pos);
    }
}

#include "mainwindow.moc"